package com.goods.order.service;

import com.goods.entity.Order;
import com.goods.entity.Orderitem;
import com.goods.mapper.CartitemMapper;
import com.goods.mapper.OrderMapper;
import com.goods.mapper.OrderitemMapper;
import com.goods.povos.CartPovo;
import com.goods.povos.OrderPovo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    private CartitemMapper cartitemMapper;
    @Autowired
    private  OrderMapper   orderMapper;
    @Autowired
    private  OrderitemMapper   orderitemMapper;


    public List<OrderPovo> getOdersByUid(String uid) {
        return   orderMapper.selectOrdersByUid(uid);
    }
    public OrderPovo getOrderPovoByOid(String oid) {
        // TODO Auto-generated method stub
        return   orderMapper.selectOrderPovoByOid(oid);
    }
    public void changeOrderStatus(Order order) {
        // TODO Auto-generated method stub
        orderMapper.updateStautsByOid(order);
    }

    @Transactional
    public Order addOrder(BigDecimal total, String address, String[] ids,String uid) {
        // TODO Auto-generated method stub

        //1 生成大订单
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String  ordertime  =  sdf.format(new Date());//下单日期
        Integer   status =   1;  //  状态  未支付

		/*User  u =  (User) session.getAttribute("user");
		String  uid =  u.getUid();// waijian
*/		Order  order =   new Order(null, ordertime, total, status, address, uid);


        orderMapper.insert(order);

        //2 生成小订单们
        // 根据 ids  把所有的   购物车条目  查回来
        // select  *  from   cartitem  where  cartItemId  in(?,?m?...)

        List<CartPovo>  cart_povos= cartitemMapper.selectCartPovoIn(Arrays.asList(ids));
        List<Orderitem>   orderitems =  new ArrayList<Orderitem>();
        for (CartPovo cartPovo : cart_povos) {
            Integer  quantity =  cartPovo.getCartitem().getQuantity();
            BigDecimal  subtotal =  cartPovo.getSubtotal();
            String bid =   cartPovo.getBid();
            String bname =  cartPovo.getBname();
            BigDecimal   currprice =  cartPovo.getCurrprice();
            String   imageB  =  cartPovo.getImageB();
            String   oid =  order.getOid();
            Orderitem  item =
                    new Orderitem(null, quantity, subtotal, bid, bname, currprice, imageB, oid);

            orderitems.add(item);
        }
        //批量插入  小订单
        orderitemMapper.insertBatch(orderitems);

        //3 删除  购物车条目们
        cartitemMapper.deleteBatchByIds(ids);

        return   order ;

    }

    public List<OrderPovo> getOrdersAll() {
        return orderMapper.getOrdersAll();
    }
}
